﻿// <copyright file="Datatable.cs" company="ThorIndustry">Copyright (c) ThorIndustry. All rights reserved.</copyright>

using System.Collections.Generic;

public class Datatable<T> : IDatatableControl, IDatatable<T> where T : IDatatableElement
{
    private Dictionary<string, T> datatable = new Dictionary<string, T>();

    public IEnumerable<string> Keys
    {
        get
        {
            return this.datatable.Keys;
        }
    }

    public IEnumerable<T> Values
    {
        get
        {
            return this.datatable.Values;
        }
    }

    public void LoadData(UnityEngine.TextAsset textAsset)
    {
        if (null == textAsset)
        {
            return;
        }

        try
        {
            // Try to load some data from the textAsset.
            System.Xml.Serialization.XmlRootAttribute rootAttribute = new System.Xml.Serialization.XmlRootAttribute("Datatable");
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<T>), rootAttribute);
            List<T> elements = (List<T>)serializer.Deserialize(new System.IO.StringReader(textAsset.text));

            if (null == elements)
            {
                UnityEngine.Debug.LogError(string.Format("[Datatable] LoadData : The datatable<LoadData : The datatable<{0}> cannot load data for textAsset : {1}.", typeof(T).ToString(), textAsset.name));
                return;
            }

            for (int i = 0; i < elements.Count; ++i)
            {
                this.LoadDatatableElement(elements[i]);
            }
        }
        catch (System.Exception ex)
        {
            UnityEngine.Debug.LogError(string.Format("[Datatable] LoadData : The datatable<{0}> cannot load data for textAsset : {1}.\nException raised : {2}", typeof(T).ToString(), textAsset.name, ex.ToString()));
        }
    }

    public void LoadData(System.Collections.Generic.IEnumerable<UnityEngine.TextAsset> textAssets)
    {
        if (null == textAssets)
        {
            return;
        }

        foreach (UnityEngine.TextAsset textAsset in textAssets)
        {
            this.LoadData(textAsset);
        }
    }

    public bool TryGetValue(string key, out T value)
    {
        return this.datatable.TryGetValue(key, out value);
    }

    public T GetValue(string key)
    {
        if (this.datatable.ContainsKey(key))
        {
            return this.datatable[key];
        }

        return default(T);
    }

    public T[] GetValues()
    {
        List<T> values = new List<T>();
        foreach (KeyValuePair<string, T> kvp in this.datatable)
        {
            values.Add(kvp.Value);
        }

        return values.ToArray();
    }

    protected virtual void LoadDatatableElement(T element)
    {
        this.datatable.Add(element.Name, element);
    }
}
